package com.googlecode.restitory.gae;

import java.util.List;

import com.googlecode.mycontainer.commons.regex.RegexUtil;

public class AuthKey {

	private String user;

	private long date;

	private String service;

	private String key;

	public AuthKey() {

	}

	public AuthKey(String user, long date, String service, String key) {
		super();
		this.user = user;
		this.date = date;
		this.service = service;
		this.key = key;
	}

	public String getUser() {
		return user;
	}

	public AuthKey setUser(String user) {
		this.user = user;
		return this;
	}

	public long getDate() {
		return date;
	}

	public AuthKey setDate(long date) {
		this.date = date;
		return this;
	}

	public String getService() {
		return service;
	}

	public AuthKey setService(String service) {
		this.service = service;
		return this;
	}

	public String getKey() {
		return key;
	}

	public AuthKey setKey(String key) {
		this.key = key;
		return this;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (int) (date ^ (date >>> 32));
		result = prime * result + ((key == null) ? 0 : key.hashCode());
		result = prime * result + ((service == null) ? 0 : service.hashCode());
		result = prime * result + ((user == null) ? 0 : user.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		AuthKey other = (AuthKey) obj;
		if (date != other.date)
			return false;
		if (key == null) {
			if (other.key != null)
				return false;
		} else if (!key.equals(other.key))
			return false;
		if (service == null) {
			if (other.service != null)
				return false;
		} else if (!service.equals(other.service))
			return false;
		if (user == null) {
			if (other.user != null)
				return false;
		} else if (!user.equals(other.user))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return new StringBuilder().append(key).append(':').append(user).append(':').append(date).append(':')
				.append(service).toString();
	}

	public static AuthKey read(String str) {
		List<String> groups = RegexUtil.groups("^([0-9a-f]{256}):([^:]+):([0-9]+):((.*))$", str);
		AuthKey ret = new AuthKey();
		ret.setKey(groups.get(1));
		ret.setUser(groups.get(2));
		ret.setDate(Long.parseLong(groups.get(3)));
		ret.setService(groups.get(4));
		return ret;
	}

	public String toDataString() {
		return new StringBuilder().append(user).append(':').append(date).append(':').append(service).toString();
	}
}
